package com.jingdianjichi.gateway.filter;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关过滤器,拦截前端所有的请求,去解析Token的,认证那里做的是认证和授权来的
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter {

    private static final String LOGIN_ID="loginId";

    //解析Token即可
    @Override
    @SneakyThrows
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //从exchange中获得所有的东西
        ServerHttpRequest request = exchange.getRequest();

        ServerHttpRequest.Builder mutate = request.mutate();        //这个是非常全的

        //我们现在是拦截Token,我们要做一些黑白名单的,比如我们在登录的时候是一定没有Token的,所以我们要去放行的亲
        String url = request.getURI().getPath();
        log.info("LoginFilter.filter.url:{}",url);

        //如果是登录的方法直接放行亲
        if (url.equals("/auth/user/doLogin")){      //这里你可以学黑马做成黑白名单的亲
            chain.filter(exchange);
        }

        //解析Token亲
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        //获得用户id
        String loginId = (String) tokenInfo.getLoginId();

        if (StringUtils.isEmpty(loginId)){
            throw new Exception("未获取到用户的信息");
        }

        //设置要传递的请求头亲
        mutate.header(LOGIN_ID,loginId);

        return chain.filter(exchange.mutate().request(mutate.build()).build());     //重新构建一下因为我们添加了新的请求头信息
    }
}
